/*
 * @Author: wangqizhang
 * @Date: 2024-04-30 14:59:50
 * @LastEditors: wangqizhang
 * @LastEditTime: 2024-05-12 16:43:30
 * @FilePath: /suixinji-react/src/api/request.ts
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
import axios from 'axios';
import { getSessionStorage } from '../untils';
const PRODUCTION_URL = 'http://140.143.140.185:5200/';
const DEVELOPMENT_URL = '/api';
const curUrl = () => {
  console.log(import.meta.env.MODE, 3333);

  return import.meta.env.MODE === 'development'
    ? DEVELOPMENT_URL
    : PRODUCTION_URL;
};
// axios 请求参数规范
type requestParams = {
  url: string;
  data?: any;
  needCache?: boolean;
};
// axios 请求封装
class Reauest {
  private instance: any;
  private catch: any;
  constructor() {
    this.catch = new Map(); // 缓存
    this.instance = axios.create({
      baseURL: curUrl(),
      timeout: 5000,
      headers: {
        'Content-Type': 'application/json',
      },
    });
    // 添加请求拦截器
    this.instance.interceptors.request.use((config: any) =>
      this.interceptors_request(config, this.catch)
    );
    // 添加响应拦截器
    this.instance.interceptors.response.use((respones: any) =>
      this.interceptors_response(respones)
    );
  }
  // 请求拦截器
  interceptors_request(config: any, requestCatch: any) {
    config.headers.Authorization = getSessionStorage('token');
    if (requestCatch.has(config.url)) {
      const getCatch = requestCatch.get(config.url);
      if (getCatch) {
        return new Promise((resolve) => {
          resolve(getCatch);
        });
      }
    }
    return config;
  }
  // 响应拦截器
  interceptors_response(response: any) {
    if (response.status === 200 || response.status === 201) {
      const { data } = response;
      return data;
    } else {
      return Promise.reject(response);
    }
  }
  // 封装get和post方法
  async get(params: requestParams) {
    if (params.needCache) {
      const cache = this.catch.get(params.url);
      if (cache) {
        return new Promise((resolve) => {
          resolve(cache);
        });
      } else {
        this.catch.set(params.url, null);
      }
    }
    return this.instance.get(params.url);
  }
  // 封装get和post方法
  async post(params: requestParams) {
    if (params.needCache) {
      const cache = this.catch.get(params.url);
      if (cache) {
        return new Promise((resolve) => {
          resolve(cache);
        });
      } else {
        this.catch.set(params.url, null);
      }
    }
    return this.instance.post(params.url, params.data);
  }
}
export default new Reauest();
